package com.xj.nrpc.client.manager;

import java.util.List;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.zookeeper.WatchedEvent;

import com.xj.nrpc.client.TCPClient;
import com.xj.nrpc.zk.ZookeeperFactory;

import io.netty.channel.ChannelFuture;

public class ServerWatcher implements CuratorWatcher {

	/**
	 * 执行监控内容 event 中包含了变化的内容
	 */
	@Override
	public void process(WatchedEvent event) throws Exception {
		CuratorFramework create = ZookeeperFactory.create();
		String path = event.getPath();
		create.getChildren().usingWatcher(this).forPath(path);
		List<String> forPath = create.getChildren().forPath(path);
		ChannelManager.channelFuturesClear();
		ChannelManager.realPathsClear();
		for (String p : forPath) {
			String[] ps = p.split("#");
			String ip = ps[0];
			Integer port = new Integer(ps[1]);
			Integer weight = new Integer(ps[2]) > 10 ? 10 : new Integer(ps[2]);
			if (weight > 0) {
				for (int i = 0; i < weight; i++) {
					ChannelManager.realPathsAdd(ip + "#" + port);
					ChannelFuture f = TCPClient.bootstrap.connect(ip, port).sync();
					ChannelManager.channelFuturesAdd(f);
				}
			}
		}
	}

}
